<!-- templates/inventory/instock.html -->
<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>出库管理 - 商店进销存管理系统</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

    <!-- 从 unpkg CDN 引入 ECharts -->
    <script src="https://unpkg.com/echarts@5.4.0/dist/echarts.min.js"></script>

    <!-- 引入 Toastify CSS 和 JS -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <link href="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.js"></script>

    <!-- Tailwind 配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#0FC6C2',
                        success: '#00B42A',
                        warning: '#FF7D00',
                        danger: '#F53F3F',
                        info: '#86909C'
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                },
            }
        }
    </script>

    <!-- 自定义工具类 -->
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }

            .sidebar-item {
                @apply flex items-center px-4 py-3 text-gray-600 hover:bg-gray-50 hover:text-primary transition-all duration-200;
            }

            .sidebar-item.active {
                @apply bg-primary/10 text-primary border-l-4 border-primary;
            }

            .card-shadow {
                @apply shadow-md hover:shadow-lg transition-shadow duration-300;
            }
            .input-focus {
                @apply focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary;
            }
            .btn-primary {
                @apply bg-primary text-white px-4 py-2 rounded-md hover:bg-primary/90 transition-colors;
            }
            .btn-secondary {
                @apply bg-gray-100 text-gray-600 px-4 py-2 rounded-md hover:bg-gray-200 transition-colors;
            }
            .btn-danger {
                @apply bg-danger text-white px-4 py-2 rounded-md hover:bg-danger/90 transition-colors;
            }
        }
    </style>
</head>

<body class="font-inter bg-gray-50 min-h-screen flex flex-col">
<!-- 顶部导航栏 -->
<header class="bg-white shadow-sm">
    <div class="container mx-auto px-4 py-3 flex justify-between items-center">
        <div class="flex items-center space-x-2">
            <i class="fa fa-cubes text-primary text-2xl"></i>
            <h1 class="text-xl font-bold text-gray-800">商店进销存管理系统</h1>
        </div>

        <div class="flex items-center space-x-6">
            <div class="relative">
                <input type="text" placeholder="搜索..."
                       class="pl-10 pr-4 py-2 rounded-full border border-gray-300 input-focus">
                <i class="fa fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
            </div>

            <div class="flex items-center space-x-4">
                <button class="text-gray-600 hover:text-primary transition-colors">
                    <i class="fa fa-bell-o text-xl"></i>
                </button>
                <button class="text-gray-600 hover:text-primary transition-colors">
                    <i class="fa fa-cog text-xl"></i>
                </button>
                <div class="flex items-center space-x-2 cursor-pointer">
                    <img src="https://picsum.photos/200/200" alt="用户头像" class="w-8 h-8 rounded-full object-cover">
                    <span class="text-gray-700">管理员</span>
                </div>
            </div>
        </div>
    </div>
</header>

<div class="flex flex-1 overflow-hidden">
    <!-- 侧边栏导航 -->
    <aside class="w-64 bg-white shadow-md h-[calc(100vh-64px)] overflow-y-auto transition-all duration-300">
        <nav class="py-4">
            <div class="px-4 mb-4">
                <h2 class="text-xs font-semibold text-gray-400 uppercase tracking-wider">主菜单</h2>
            </div>

            <a href="index.html" class="sidebar-item" data-path="index.html">
                <i class="fa fa-tachometer w-5 h-5 mr-3"></i>
                <span>仪表盘</span>
            </a>

            <div class="px-4 mt-6 mb-2">
                <h2 class="text-xs font-semibold text-gray-400 uppercase tracking-wider">基础信息</h2>
            </div>

            <a href="productlist.html" class="sidebar-item" data-path="productlist.html">
                <i class="fa fa-shopping-bag w-5 h-5 mr-3"></i>
                <span>商品管理</span>
            </a>

            <a href="categorylist.html" class="sidebar-item" data-path="categorylist.html">
                <i class="fa fa-th-large w-5 h-5 mr-3"></i>
                <span>类别管理</span>
            </a>

            <a href="supplierlist.html" class="sidebar-item" data-path="supplierlist.html">
                <i class="fa fa-truck w-5 h-5 mr-3"></i>
                <span>供应商管理</span>
            </a>


            <div class="px-4 mt-6 mb-2">
                <h2 class="text-xs font-semibold text-gray-400 uppercase tracking-wider">库存管理</h2>
            </div>

            <a href="warehouselist.html" class="sidebar-item" data-path="warehouselist.html">
                <i class="fa fa-archive w-5 h-5 mr-3"></i>
                <span>仓库管理</span>
            </a>

            <a href="inventorylist.html" class="sidebar-item" data-path="inventorylist.html">
                <i class="fa fa-list-alt w-5 h-5 mr-3"></i>
                <span>库存查询</span>
            </a>

            <a href="instock.html" class="sidebar-item " data-path="instock.html">
                <i class="fa fa-sign-in w-5 h-5 mr-3"></i>
                <span>入库管理</span>
            </a>

            <a href="outstock.html" class="sidebar-item active" data-path="outstock.html">
                <i class="fa fa-sign-out w-5 h-5 mr-3"></i>
                <span>出库管理</span>
            </a>

            <a href="transfer.html" class="sidebar-item" data-path="transfer.html">
                <i class="fa fa-exchange w-5 h-5 mr-3"></i>
                <span>转仓管理</span>
            </a>

            <div class="px-4 mt-6 mb-2">
                <h2 class="text-xs font-semibold text-gray-400 uppercase tracking-wider">统计分析</h2>
            </div>

            <a href="statistics/sales.html" class="sidebar-item" data-path="statistics/sales.html">
                <i class="fa fa-line-chart w-5 h-5 mr-3"></i>
                <span>销售统计</span>
            </a>

            <a href="statistics/inventory.html" class="sidebar-item" data-path="statistics/inventory.html">
                <i class="fa fa-pie-chart w-5 h-5 mr-3"></i>
                <span>库存分析</span>
            </a>

            <div class="px-4 mt-6 mb-2">
                <h2 class="text-xs font-semibold text-gray-400 uppercase tracking-wider">系统设置</h2>
            </div>

            <a href="salesman.html" class="sidebar-item" data-path="salesman.html">
                <i class="fa fa-user-circle w-5 h-5 mr-3"></i>
                <span>用户管理</span>
            </a>


            <a href="backup.html" class="sidebar-item" data-path="system/logs.html">
                <i class="fa fa-history w-5 h-5 mr-3"></i>
                <span>数据库备份与恢复</span>
            </a>
        </nav>
    </aside>

    <!-- 主内容区域 -->
    <main class="flex-1 overflow-y-auto bg-gray-50 p-6">
        <div class="container mx-auto">
            <!-- 页面标题 -->
            <div class="mb-6">
                <h2 class="text-[clamp(1.5rem,3vw,2rem)] font-bold text-gray-800">出库管理</h2>
                <p class="text-gray-500 mt-1">创建和管理商品出库订单</p>
            </div>

            <!-- 订单状态筛选和搜索 -->
            <div class="mb-6 flex flex-col md:flex-row md:items-center md:justify-between gap-4">
                <div class="flex flex-wrap gap-3">
                    <div class="relative">
                        <select id="statusFilter" class="pl-3 pr-10 py-2 rounded-md border border-gray-300 input-focus appearance-none">
                            <option value="">所有状态</option>
                            <option value="pending">待处理</option>
                            <option value="completed">已完成</option>
                            <option value="failed">已失败</option>
                            <!--                            <option value="cancel">已取消</option>-->
                        </select>
                        <i class="fa fa-chevron-down absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 pointer-events-none"></i>
                    </div>

                    <div class="relative">
                        <input type="text" id="searchInput" placeholder="搜索订单号"
                               class="pl-10 pr-4 py-2 rounded-md border border-gray-300 input-focus">
                        <i class="fa fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                    </div>

                    <button id="searchBtn" class="btn-primary flex items-center">
                        <i class="fa fa-search mr-2"></i> 搜索
                    </button>
                </div>

                <button id="createOrderBtn" class="btn-primary flex items-center">
                    <i class="fa fa-plus mr-2"></i> 新建出库订单
                </button>
            </div>

            <!-- 出库订单列表 -->
            <div class="bg-white rounded-xl p-6 card-shadow mb-6">
                <h3 class="text-lg font-semibold text-gray-800 mb-4">出库订单列表</h3>

                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead>
                        <tr class="border-b border-gray-200">
                            <th class="py-3 text-left text-sm font-medium text-gray-500">订单号</th>
                            <th class="py-3 text-left text-sm font-medium text-gray-500">日期</th>
                            <th class="py-3 text-left text-sm font-medium text-gray-500">业务员</th>
                            <th class="py-3 text-left text-sm font-medium text-gray-500">仓库</th>
                            <th class="py-3 text-left text-sm font-medium text-gray-500">状态</th>
                            <th class="py-3 text-left text-sm font-medium text-gray-500">商品数量</th>
                            <th class="py-3 text-left text-sm font-medium text-gray-500">操作</th>
                        </tr>
                        </thead>
                        <tbody id="orderTable">
                        <!-- 数据将通过JS动态渲染 -->
                        <tr>
                            <td colspan="8" class="py-4 text-center">
                                <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
                                <p class="mt-2 text-gray-600">加载订单数据中...</p>
                            </td>
                        </tr>
                        </tbody>
                    </table>
                </div>

                <!-- 分页控件 -->
                <div class="mt-6 flex justify-between items-center">
                    <div class="text-sm text-gray-500" id="paginationInfo">共 0 条记录</div>
                    <div class="flex space-x-1" id="paginationControls">
                        <!-- 分页控件将通过JS动态渲染 -->
                    </div>
                </div>
            </div>

            <!-- 出库订单创建表单 (默认隐藏) -->
            <div id="orderFormContainer" class="bg-white rounded-xl p-6 card-shadow hidden">
                <div class="flex justify-between items-center mb-6">
                    <h3 class="text-lg font-semibold text-gray-800">新建出库订单</h3>
                    <button id="closeFormBtn" class="text-gray-500 hover:text-gray-700">
                        <i class="fa fa-times text-xl"></i>
                    </button>
                </div>

                <form id="orderForm" class="space-y-6">
                    <!-- 订单基本信息 -->
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-6">

                        <!-- 修改后 - 添加隐藏字段存储完整时间 -->
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">订单日期</label>
                            <input type="datetime-local" id="orderDate" class="w-full px-3 py-2 rounded-md border border-gray-300 input-focus" value="" required>
                            <input type="hidden" id="orderDateTimeWithSeconds" name="orderDateTimeWithSeconds">
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">业务员</label>
                            <div class="relative">
                                <select id="salesmanSelect" class="w-full pl-3 pr-10 py-2 rounded-md border border-gray-300 input-focus appearance-none">
                                    <option value="">选择业务员</option>
                                    <!-- 业务员数据将通过JS动态加载 -->
                                </select>
                                <i class="fa fa-chevron-down absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 pointer-events-none"></i>
                            </div>
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">仓库</label>
                            <div class="relative">
                                <select id="warehouseSelect" class="w-full pl-3 pr-10 py-2 rounded-md border border-gray-300 input-focus appearance-none">
                                    <option value="">选择仓库</option>
                                    <!-- 仓库数据将通过JS动态加载 -->
                                </select>
                                <i class="fa fa-chevron-down absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 pointer-events-none"></i>
                            </div>
                        </div>
                    </div>

                    <!-- 订单商品明细 -->
                    <div>
                        <div class="flex justify-between items-center mb-3">
                            <h4 class="text-base font-medium text-gray-800">订单商品明细</h4>
                            <button type="button" id="addProductBtn" class="text-primary hover:text-primary/80 flex items-center">
                                <i class="fa fa-plus-circle mr-1"></i> 添加商品
                            </button>
                        </div>

                        <div class="overflow-x-auto">
                            <table class="w-full" id="productTable">
                                <thead>
                                <tr class="bg-gray-50 border border-gray-200">
                                    <th class="py-2 px-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">商品</th>
                                    <th class="py-2 px-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">数量</th>
                                    <th class="py-2 px-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                                </tr>
                                </thead>
                                <tbody>
                                <!-- 商品行将通过JS动态添加 -->
                                <tr id="emptyProductRow">
                                    <td colspan="3" class="py-6 text-center text-gray-500">
                                        <i class="fa fa-info-circle mr-2"></i> 请添加商品到订单
                                    </td>
                                </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <!-- 订单备注 -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">备注</label>
                        <textarea id="orderRemark" rows="3" class="w-full px-3 py-2 rounded-md border border-gray-300 input-focus" placeholder="输入订单备注信息"></textarea>
                    </div>

                    <!-- 表单操作按钮 -->
                    <div class="flex justify-end space-x-3">
                        <button type="button" id="cancelOrderBtn" class="btn-secondary">取消</button>
                        <button type="button" id="saveOrderBtn" class="btn-primary">保存订单</button>
                        <button type="button" id="confirmOrderBtn" class="btn-primary bg-success">确认出库</button>
                    </div>
                </form>
            </div>
        </div>
    </main>
</div>

<!-- 页脚 -->
<footer class="bg-white py-4 border-t border-gray-200">
    <div class="container mx-auto px-4 text-center text-gray-500 text-sm">
        <p>© 2025 商店进销存管理系统 - 版权所有</p>
    </div>
</footer>

<!-- 商品选择模态框（修改后） -->
<div id="productModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
    <div class="bg-white rounded-lg shadow-xl w-full max-w-3xl max-h-[90vh] flex flex-col">
        <div class="p-4 border-b border-gray-200 flex justify-between items-center">
            <h3 class="text-lg font-semibold text-gray-800">选择商品</h3>
            <button class="text-gray-500 hover:text-gray-700" onclick="document.getElementById('productModal').classList.add('hidden')">
                <i class="fa fa-times"></i>
            </button>
        </div>
        <div class="p-4 flex-1 overflow-y-auto">
            <div class="relative mb-4">
                <input type="text" id="productSearchInput" placeholder="搜索商品名称/编号"
                       class="w-full pl-10 pr-4 py-2 rounded-md border border-gray-300 input-focus">
                <i class="fa fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
            </div>
            <div id="productListContainer" class="space-y-3">
                <!-- 商品列表和分页将通过JS动态渲染 -->
            </div>
            <div id="productPagination" class="mt-4 flex justify-between items-center"></div>
        </div>
        <div class="flex justify-end p-4 border-t border-gray-200">
            <button class="btn-secondary" onclick="document.getElementById('productModal').classList.add('hidden')">取消</button>
        </div>
    </div>
</div>
<!-- 订单详情模态框 -->
<div id="orderDetailModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden"></div>

<script>
    // 权限检查函数
    function hasPermission(permissionCode) {
        // 从localStorage或cookie中获取用户权限列表
        const userPermissions = JSON.parse(localStorage.getItem('userPermissions') || '[]');
        return userPermissions.includes(permissionCode);
    }

    // 根据角色隐藏/展示按钮
    const applyRolePermissions = () => {
        fetch('/user-info')
            .then(response => {
                if (!response.ok) {
                    throw new Error(`获取用户信息失败: 状态码 ${response.status}`);
                }
                return response.json(); // 解析JSON格式响应
            })
            .then(data => {
                console.log('用户信息响应:', data);

                // 检查响应结构是否正确
                if (data.code !== "200" || !data.data) {
                    throw new Error(data.message || '响应数据格式错误');
                }

                const userData = data.data;
                const authorities = userData.authorities;

                // 使用正则表达式提取角色信息（假设authorities格式为"Roles:[ROLE_USER]"）
                const roles = authorities.match(/Roles:\[(.*?)\]/);
                if (roles) {
                    const roleList = roles[1].split(","); // 注意：后端返回的是ROLE_USER，无空格，使用逗号直接分割
                    console.log('用户角色:', roleList);

                    // 存储用户权限到localStorage
                    localStorage.setItem('userPermissions', JSON.stringify(roleList));

                    if (!roleList.includes("ROLE_ADMIN")) {
                        // 隐藏管理员专属按钮
                        const confirmOrderBtn = document.getElementById('confirmOrderBtn');
                        if (confirmOrderBtn) {
                            confirmOrderBtn.style.display = 'none';
                        }

                        // 隐藏需要管理员权限的按钮
                        document.querySelectorAll('[data-permission]').forEach(button => {
                            const requiredPermission = button.getAttribute('data-permission');
                            if (!hasPermission(requiredPermission)) {
                                button.style.display = 'none';
                            }
                        });
                    }
                } else {
                    console.warn('未找到角色信息，原始数据:', authorities);
                }
            })
            .catch(error => {
                console.error('获取用户信息失败:', error);
                Toastify({
                    text: '获取用户权限失败，请重新登录',
                    duration: 3000,
                    gravity: 'top',
                    position: 'right',
                    backgroundColor: '#f44336'
                }).showToast();
            });
    };

    // 确保在商品数据加载完成后再次应用权限
    const ensurePermissionsApplied = () => {
        // 如果数据是异步加载的，可能需要在数据加载完成后再次调用
        setTimeout(() => {
            applyRolePermissions();
        }, 500); // 等待500毫秒，确保数据加载完成
    };
    // 全局变量
    let currentPage = 0; // 当前页码
    let totalPages = 0; // 总页数
    let currentOrderId = null; // 当前操作的订单ID
    let productRows = []; // 订单商品行数据

    // 新增全局数据存储
    let globalData = {
        products: {},        // 商品ID: {name: '商品名', ...}
        salesmen: {},        // 业务员ID: '业务员名'
        warehouses: {}       // 仓库ID: '仓库名'
    };
    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', () => {
        initSidebarNavigation();
        setCurrentPageActive();
        initEventListeners();

        // 延迟执行，确保所有资源都加载完成
        setTimeout(() => {
            loadSalesmen();
            loadWarehouses();
            loadallProducts();
            loadOrders();
            // 自动填充当前日期时间（精确到秒）
            autoFillOrderDateTime();
        }, 300); // 延迟300毫秒

        // 应用角色权限
        applyRolePermissions();

        // 确保数据加载完成后再次应用权限
        ensurePermissionsApplied();

        // 绑定按钮事件
        document.addEventListener('click', (e) => {
            // 处理编辑按钮
            if (e.target.closest('.edit-btn')) {
                const button = e.target.closest('.edit-btn');
                const orderId = parseInt(button.getAttribute('data-id'));
                editOrder(orderId);
            }

            // 处理删除按钮
            if (e.target.closest('.delete-btn')) {
                const button = e.target.closest('.delete-btn');
                const orderId = parseInt(button.getAttribute('data-id'));
                cancelOrder(orderId);
            }

            // 处理删除按钮
            if (e.target.closest('.execute-btn')) {
                const button = e.target.closest('.execute-btn');
                const orderId = parseInt(button.getAttribute('data-id'));
                executeOrder(orderId);
            }
        });
    });

    // 自动填充订单日期时间（精确到秒）
    const autoFillOrderDateTime = () => {
        const now = new Date();

        // 格式化为 YYYY-MM-DDTHH:MM（用于显示）
        const displayFormat = now.toISOString().slice(0, 16);

        // 格式化为 YYYY-MM-DDTHH:MM:SS（用于存储）
        const fullFormat = now.toISOString().slice(0, 19);

        // 设置显示值
        document.getElementById('orderDate').value = displayFormat;

        // 设置隐藏字段的完整值
        document.getElementById('orderDateTimeWithSeconds').value = fullFormat;
    };


    // 初始化事件监听器
    const initEventListeners = () => {
        // 搜索按钮点击事件
        document.getElementById('searchBtn').addEventListener('click', () => {
            loadOrders(0); // 从第一页开始加载
        });

        // 状态筛选下拉框变化事件
        document.getElementById('statusFilter').addEventListener('change', () => {
            loadOrders(0); // 从第一页开始加载
        });

        // 搜索输入框回车事件
        document.getElementById('searchInput').addEventListener('keyup', (e) => {
            if (e.key === 'Enter') {
                loadOrders(0); // 从第一页开始加载
            }
        });

        // 创建订单按钮点击事件
        document.getElementById('createOrderBtn').addEventListener('click', showOrderForm);

        // 关闭表单按钮点击事件
        document.getElementById('closeFormBtn').addEventListener('click', hideOrderForm);

        // 取消订单按钮点击事件
        document.getElementById('cancelOrderBtn').addEventListener('click', hideOrderForm);

        // 保存订单按钮点击事件
        document.getElementById('saveOrderBtn').addEventListener('click', saveOrder);

        // 确认订单按钮点击事件
        document.getElementById('confirmOrderBtn').addEventListener('click', confirmOrder);

        // 添加商品按钮点击事件
        document.getElementById('addProductBtn').addEventListener('click', showProductModal);

        // 设置今天的日期为默认值
        document.getElementById('orderDate').value = formatted;

        // 监听仓库选择框的变化
        document.getElementById('warehouseSelect').addEventListener('change', () => {
            loadProducts();
        });
    };
    const now = new Date();
    // 格式化为 YYYY-MM-DDTHH:MM 格式
    const formatted = now.toISOString().slice(0, 16);

    // 从后端API加载出库订单数据
    const loadOrders = (page = 0) => {
        const orderTable = document.getElementById('orderTable');
        const paginationInfo = document.getElementById('paginationInfo');
        const paginationControls = document.getElementById('paginationControls');

        // 显示加载中状态
        orderTable.innerHTML = `
            <tr>
                <td colspan="8" class="py-4 text-center">
                    <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
                    <p class="mt-2 text-gray-600">加载订单数据中...</p>
                </td>
            </tr>
        `;

        // 获取筛选参数
        const statusFilter = document.getElementById('statusFilter').value;
        const searchInput = document.getElementById('searchInput').value;

        // 构建查询参数
        const queryParams = new URLSearchParams({
            page: page,
            size: 10,
            ...(statusFilter && { status: statusFilter }),
            ...(searchInput && { keyword: searchInput })
        });

        // 调用后端API获取订单数据
        fetch(`/outStockOrder?${queryParams}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP错误! 状态码: ${response.status}`);
                }
                return response.json();
            })
            .then(apiResponse => {
                console.log('API响应数据:', apiResponse);
                orderTable.innerHTML = '';

                // 验证响应结构
                if (!apiResponse || apiResponse.code !== "200" || !apiResponse.data) {
                    throw new Error(apiResponse?.message || 'API响应失败');
                }

                // 解构数据
                const { content: orders, totalElements, totalPages, pageable } = apiResponse.data;
                currentPage = pageable.pageNumber; // 后端从0开始，前端从1开始

                // 更新分页信息
                const displayPage = currentPage + 1;
                paginationInfo.textContent = `共 ${totalElements} 条记录，当前第 ${displayPage} 页`;
                updatePaginationControls(totalPages, displayPage);

                // 处理无数据情况
                if (orders.length === 0) {
                    orderTable.innerHTML = `
                        <tr>
                            <td colspan="8" class="py-4 text-center text-gray-500">没有找到符合条件的出库订单</td>
                        </tr>
                    `;
                    return;
                }

                // 渲染订单数据
                orders.forEach(order => {
                    const row = document.createElement('tr');
                    row.className = 'border-b border-gray-100 hover:bg-gray-50';

                    // 从API数据中提取ID（注意：这里获取的是ID，非名称）
                    const orderId = order.orderId;
                    const orderDate = formatDate(order.orderDate) || '未知日期';
                    const salesmanId = order.salesmanId || 0;
                    const warehouseId = order.warehouseId || 0;
                    const status = order.status || '未知';
                    const productCount = order.outStockDetails?.length || 0;

                    // 通过全局数据获取名称
                    const salesmanName = globalData.salesmen[salesmanId] || '未知业务员';
                    const warehouseName = globalData.warehouses[warehouseId] || '未知仓库';

                    // 确定状态标签样式
                    let statusClass = '';
                    let statusText = '';
                    switch (status) {
                        case 'pending':
                            statusClass = 'bg-blue-100 text-blue-800';
                            statusText = '待处理';
                            break;
                        case 'completed':
                            statusClass = 'bg-green-100 text-green-800';
                            statusText = '已完成';
                            break;
                        case 'failed':
                            statusClass = 'bg-red-100 text-red-800';
                            statusText = '已失败';
                            break;
                        case 'cancel':
                            statusClass = 'bg-gray-100 text-gray-800';
                            statusText = '已取消';
                            break;
                        default:
                            statusClass = 'bg-gray-100 text-gray-800';
                            statusText = '未知';
                    }

                    // 构建操作按钮
                    let actionButtons = '';
                    if (status === 'pending') {
                        actionButtons = `
                            <button class="text-primary mr-2" onclick="viewOrderDetails(${orderId})">
                                <i class="fa fa-eye"></i> 查看
                            </button>
                            <button data-id="${orderId}" class="edit-btn text-primary mr-2" data-permission="OUTSTOCK_EDIT">
                              <i class="fa fa-pencil"></i> 编辑
                            </button>
                            <button data-id="${orderId}" class="execute-btn text-danger" data-permission="OUTSTOCK_DELETE">
                              <i class="fa fa-check"></i> 执行
                            </button>
                            <button data-id="${orderId}" class="delete-btn text-danger" data-permission="OUTSTOCK_DELETE">
                              <i class="fa fa-times"></i> 取消
                            </button>
                        `;
                    } else {
                        actionButtons = `
                            <button class="text-primary" onclick="viewOrderDetails(${orderId})">
                                <i class="fa fa-eye"></i> 查看
                            </button>
                            <button data-id="${orderId}" class="delete-btn text-danger" data-permission="CATEGORY_DELETE">
                              <i class="fa fa-times"></i> 删除
                            </button>
                        `;
                    }

                    // 格式化显示ID和名称

                    const formattedSalesman = formatIdName(salesmanId, salesmanName);
                    const formattedWarehouse = formatIdName(warehouseId, warehouseName);

                    row.innerHTML = `
                        <td class="py-3 text-sm text-gray-600">#${orderId}</td>

                        <td class="py-3 text-sm text-gray-600">${orderDate}</td>
                        <td class="py-3 text-sm text-gray-600">${formattedSalesman}</td>
                        <td class="py-3 text-sm text-gray-600">${formattedWarehouse}</td>
                        <td class="py-3 text-sm">
                            <span class="px-2 py-1 rounded-full text-xs font-medium ${statusClass}">${statusText}</span>
                        </td>
                        <td class="py-3 text-sm text-gray-600">${productCount}</td>
                        <td class="py-3 text-sm text-gray-600">
                            ${actionButtons}
                        </td>
                    `;
                    orderTable.appendChild(row);
                });
            })
            .catch(error => {
                console.error('加载订单数据失败:', error);
                orderTable.innerHTML = `
                    <tr>
                        <td colspan="8" class="py-4 text-center text-red-500">
                            <i class="fa fa-exclamation-circle mr-2"></i> 加载订单数据失败，请稍后重试
                        </td>
                    </tr>
                `;

                Toastify({
                    text: `加载订单数据失败: ${error.message}`,
                    duration: 3000,
                    gravity: "top",
                    position: "right",
                    backgroundColor: "#f44336",
                }).showToast();
            });
        // 确保重新应用角色权限
        setTimeout(() => {
            applyRolePermissions();
        }, 100); // 等待数据加载完成
    };

    // 辅助函数：格式化ID和名称的显示
    function formatIdName(id, name) {
        if (id === 0) return name; // 未知情况直接显示名称
        return `<div class="flex flex-col">
                <span class="font-medium">${name}</span>
                <span class="text-xs text-gray-500">ID: ${id}</span>
            </div>`;
    }

    // 更新分页控件
    const updatePaginationControls = (totalPages, currentPage) => {
        const controls = document.getElementById('paginationControls');
        controls.innerHTML = '';

        // 上一页按钮
        const prevBtn = document.createElement('button');
        prevBtn.className = `px-3 py-1 border border-gray-300 rounded-md text-gray-500 hover:bg-gray-50 ${currentPage === 1 ? 'opacity-50 cursor-not-allowed' : ''}`;
        prevBtn.disabled = currentPage === 1;
        prevBtn.innerHTML = '<i class="fa fa-chevron-left"></i>';
        prevBtn.addEventListener('click', () => {
            if (currentPage > 1) {
                loadOrders(currentPage - 2); // 转换为后端页码（前端页码-1）
            }
        });
        controls.appendChild(prevBtn);

        // 页码按钮 (显示当前页及前后两页)
        const startPage = Math.max(1, currentPage - 2);
        const endPage = Math.min(totalPages, currentPage + 2);

        for (let i = startPage; i <= endPage; i++) {
            const pageBtn = document.createElement('button');
            pageBtn.className = `px-3 py-1 border rounded-md text-gray-700 hover:bg-gray-50 ${i === currentPage ? 'border-primary bg-primary text-white' : ''}`;
            pageBtn.textContent = i;
            pageBtn.addEventListener('click', () => {
                loadOrders(i - 1); // 转换为后端页码（前端页码-1）
            });
            controls.appendChild(pageBtn);
        }

        // 下一页按钮
        const nextBtn = document.createElement('button');
        nextBtn.className = `px-3 py-1 border border-gray-300 rounded-md text-gray-500 hover:bg-gray-50 ${currentPage === totalPages ? 'opacity-50 cursor-not-allowed' : ''}`;
        nextBtn.disabled = currentPage === totalPages;
        nextBtn.innerHTML = '<i class="fa fa-chevron-right"></i>';
        nextBtn.addEventListener('click', () => {
            if (currentPage < totalPages) {
                loadOrders(currentPage); // 转换为后端页码（前端页码-1）
            }
        });
        controls.appendChild(nextBtn);
    };

    // 显示订单表单
    const showOrderForm = () => {
        // 重置表单
        document.getElementById('orderForm').reset();
        productRows = [];
        renderProductTable();

        // 显示表单容器
        document.getElementById('orderFormContainer').classList.remove('hidden');

        // 滚动到表单顶部
        document.getElementById('orderFormContainer').scrollIntoView({ behavior: 'smooth' });

        // 重置当前订单ID
        currentOrderId = null;
    };

    // 隐藏订单表单
    const hideOrderForm = () => {
        // 确认对话框
        if (productRows.length > 0 || currentOrderId !== null) {
            if (!confirm("确定要取消当前操作吗？未保存的更改将丢失。")) {
                return;
            }
        }

        // 隐藏表单容器
        document.getElementById('orderFormContainer').classList.add('hidden');

        // 重置当前订单ID
        currentOrderId = null;
    };

    // 保存订单
    const saveOrder = () => {
        // 验证表单
        if (!validateOrderForm()) {
            return;
        }

        // 构建订单数据
        const orderData = buildOrderData();

        // 显示加载状态
        const saveButton = document.getElementById('saveOrderBtn');
        saveButton.disabled = true;
        saveButton.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 保存中...';

        // 调用API
        const apiUrl = currentOrderId ? `/outStockOrder/${currentOrderId}` : `/outStockOrder`;
        const httpMethod = currentOrderId ? 'PUT' : 'POST';

        fetch(apiUrl, {
            method: httpMethod,
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(orderData),
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP错误! 状态码: ${response.status}`);
                }
                return response.json();
            })
            .then(apiResponse => {
                console.log('保存订单API响应:', apiResponse);

                // 恢复按钮状态
                saveButton.disabled = false;
                saveButton.innerHTML = '保存订单';

                // 处理响应
                if (apiResponse) {
                    Toastify({
                        text: currentOrderId ? "订单更新成功" : "订单创建成功",
                        duration: 3000,
                        gravity: "top",
                        position: "right",
                        backgroundColor: "#4CAF50",
                    }).showToast();

                    // 刷新订单列表
                    loadOrders();

                    // 如果是新建订单，更新当前订单ID
                    if (!currentOrderId) {
                        currentOrderId = apiResponse.orderId;
                    }
                } else {
                    const errorMsg = apiResponse && apiResponse.message
                        ? apiResponse.message
                        : currentOrderId ? '更新失败：未知错误' : '创建失败：未知错误';
                    Toastify({
                        text: errorMsg,
                        duration: 3000,
                        gravity: "top",
                        position: "right",
                        backgroundColor: "#f44336",
                    }).showToast();
                }
            })
            .catch(error => {
                console.error('保存订单失败:', error);
                // 恢复按钮状态
                saveButton.disabled = false;
                saveButton.innerHTML = '保存订单';
                // 显示错误信息
                Toastify({
                    text: `保存订单失败: ${error.message}`,
                    duration: 3000,
                    gravity: "top",
                    position: "right",
                    backgroundColor: "#f44336",
                }).showToast();
            });
    };

    // 确认订单（执行出库）
    const confirmOrder = () => {
        // 验证表单
        if (!validateOrderForm()) {
            return;
        }

        // 确认对话框
        if (!confirm("确定要执行此出库订单吗？执行后将更新库存数据。")) {
            return;
        }

        // 构建订单数据
        const orderData = buildOrderData();

        // 显示加载状态
        const confirmButton = document.getElementById('confirmOrderBtn');
        confirmButton.disabled = true;
        confirmButton.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 处理中...';

        // 调用API
        fetch(`/outStockOrder/${currentOrderId || 0}/execute`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(orderData),
        })
            .then(response => {
                // 对于204响应，不需要解析JSON
                if (response.status === 204) {
                    return null; // 表示操作成功但无返回数据
                }
                if (!(response.ok)) {
                    // 尝试解析响应中的JSON错误信息
                    return response.json().catch(() => ({})) // 解析失败则返回空对象
                        .then(errorData => {
                            // 构建包含HTTP状态码和服务器错误信息的错误
                            const errorMessage = errorData.message
                                ? `HTTP错误 ${response.status}: ${errorData.message}`
                                : `HTTP错误 ${response.status}`;
                            throw new Error(errorMessage);
                        });
                }
                return response.json();
            })
            .then(apiResponse => {
                console.log('确认订单API响应:', apiResponse);

                // 恢复按钮状态
                confirmButton.disabled = false;
                confirmButton.innerHTML = '确认出库';

                if (apiResponse === null) {
                    // 处理204响应
                    Toastify({
                        text: "出库操作成功，库存已更新",
                        duration: 3000,
                        gravity: "top",
                        position: "right",
                        backgroundColor: "#4CAF50",
                    }).showToast();

                    // 刷新订单列表
                    loadOrders();
                    // 隐藏订单表单
                    hideOrderForm();
                } else if (apiResponse) {
                    // 处理失败响应（如有数据返回）
                    const errorMsg = apiResponse && apiResponse.message
                        ? apiResponse.message
                        : '执行失败：未知错误';
                    Toastify({
                        text: errorMsg,
                        duration: 3000,
                        gravity: "top",
                        position: "right",
                        backgroundColor: "#4CAF50",
                    }).showToast();

                    // 刷新订单列表
                    loadOrders();
                } else {
                    const errorMsg = apiResponse && apiResponse.message
                        ? apiResponse.message
                        : '执行失败：未知错误';
                    Toastify({
                        text: errorMsg,
                        duration: 3000,
                        gravity: "top",
                        position: "right",
                        backgroundColor: "#f44336",
                    }).showToast();
                }
            })
            .catch(error => {
                console.error('确认订单失败:', error);
                // 恢复按钮状态
                confirmButton.disabled = false;
                confirmButton.innerHTML = '确认出库';
                // 显示错误信息
                Toastify({
                    text: `确认订单失败: ${error.message}`,
                    duration: 3000,
                    gravity: "top",
                    position: "right",
                    backgroundColor: "#f44336",
                }).showToast();
            });
    };
    // 通用分页数据加载函数（已在原代码中存在，优化参数传递）
    const loadPagedData = (url, callback, params = {}) => {
        const queryParams = new URLSearchParams({
            page: '0',
            size: '10',
            ...params
        });
        fetch(`${url}?${queryParams}`)
            .then(res => res.ok ? res.json() : Promise.reject(new Error(`状态码: ${res.status}`)))
            .then(apiResponse => {
                if (apiResponse.code === "200" && apiResponse.data?.content) {
                    callback(apiResponse.data.content, apiResponse.data.totalPages);
                } else {
                    throw new Error(apiResponse.message || "数据格式错误");
                }
            })
            .catch(error => {
                console.error('加载失败:', error);
                Toastify({ text: `加载失败: ${error.message}`, ...toastConfig }).showToast();
            });
    };

    // 配置Toast样式
    const toastConfig = {
        duration: 3000,
        gravity: "top",
        position: "right",
        backgroundColor: "#f44336",
    };

    // 加载商品（修改后）
    const loadallProducts = () => {
        loadPagedData('/product', (products) => {
            window.availableProducts = products;
            // 填充全局商品数据
            products.forEach(product => {
                globalData.products[product.productId] = {
                    name: product.productName,
                    code: product.productId
                };
            });
        });
    };

    // 加载商品（修改后）
    // 从后端API加载商品数据
    const loadProducts = () => {
        const warehouseId = document.getElementById('warehouseSelect').value;
        if (!warehouseId) {
            // 如果没有选择仓库，清空商品列表或给出提示
            document.getElementById('productListContainer').innerHTML = '';
            return;
        }

        const productListContainer = document.getElementById('productListContainer');
        const productPagination = document.getElementById('productPagination');

        // 显示加载中状态
        productListContainer.innerHTML = `
                <div class="text-center text-gray-600">
                    <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
                    <p class="mt-2">加载商品数据中...</p>
                </div>
            `;


        const url = `/warehouseProduct/${warehouseId}`;

        // 调用新接口 warehouseProduct 获取商品数据
        fetch(url)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP错误! 状态码: ${response.status}`);
                }
                return response.json();
            })
            .then(apiResponse => {
                console.log('API响应数据:', apiResponse);
                productListContainer.innerHTML = '';

                // 验证响应结构
                if (!apiResponse || apiResponse.code !== "200" || !apiResponse.data) {
                    throw new Error(apiResponse?.message || 'API响应失败');
                }

                // 解构数据
                const { content: products, totalElements, totalPages, pageable } = apiResponse.data;
                currentPage = pageable.pageNumber; // 后端从0开始，前端从1开始

                // 更新分页信息
                const displayPage = currentPage + 1;
                updateProductPaginationControls(totalPages, displayPage);

                // 处理无数据情况
                if (products.length === 0) {
                    productListContainer.innerHTML = `
                            <div class="text-center text-gray-500">
                                <i class="fa fa-info-circle mr-2"></i> 没有找到符合条件的商品
                            </div>
                        `;
                    return;
                }

                // 渲染商品数据
                products.forEach(product => {
                    const productItem = document.createElement('div');
                    productItem.className = 'flex justify-between items-center p-3 border-b border-gray-200';
                    productItem.innerHTML = `
                            <span class="text-gray-600">${product.name}</span>
                            <button class="btn-primary" onclick="addProductToOrder(${product.id})">选择</button>
                        `;
                    productListContainer.appendChild(productItem);
                });
            })
            .catch(error => {
                console.error('加载商品数据失败:', error);
                productListContainer.innerHTML = `
                        <div class="text-center text-red-500">
                            <i class="fa fa-exclamation-circle mr-2"></i> 加载商品数据失败，请稍后重试
                        </div>
                    `;

                Toastify({
                    text: `加载商品数据失败: ${error.message}`,
                    duration: 3000,
                    gravity: "top",
                    position: "right",
                    backgroundColor: "#f44336",
                }).showToast();
            });
    };
    // 更新商品分页控件
    const updateProductPaginationControls = (totalPages, currentPage) => {
        const controls = document.getElementById('productPagination');
        controls.innerHTML = '';

        // 上一页按钮
        const prevBtn = document.createElement('button');
        prevBtn.className = `px-3 py-1 border border-gray-300 rounded-md text-gray-500 hover:bg-gray-50 ${currentPage === 1 ? 'opacity-50 cursor-not-allowed' : ''}`;
        prevBtn.disabled = currentPage === 1;
        prevBtn.innerHTML = '<i class="fa fa-chevron-left"></i>';
        prevBtn.addEventListener('click', () => {
            if (currentPage > 1) {
                loadProducts(currentPage - 2); // 转换为后端页码（前端页码-1）
            }
        });
        controls.appendChild(prevBtn);

        // 页码按钮 (显示当前页及前后两页)
        const startPage = Math.max(1, currentPage - 2);
        const endPage = Math.min(totalPages, currentPage + 2);

        for (let i = startPage; i <= endPage; i++) {
            const pageBtn = document.createElement('button');
            pageBtn.className = `px-3 py-1 border rounded-md text-gray-700 hover:bg-gray-50 ${i === currentPage ? 'border-primary bg-primary text-white' : ''}`;
            pageBtn.textContent = i;
            pageBtn.addEventListener('click', () => {
                loadProducts(i - 1); // 转换为后端页码（前端页码-1）
            });
            controls.appendChild(pageBtn);
        }

        // 下一页按钮
        const nextBtn = document.createElement('button');
        nextBtn.className = `px-3 py-1 border border-gray-300 rounded-md text-gray-500 hover:bg-gray-50 ${currentPage === totalPages ? 'opacity-50 cursor-not-allowed' : ''}`;
        nextBtn.disabled = currentPage === totalPages;
        nextBtn.innerHTML = '<i class="fa fa-chevron-right"></i>';
        nextBtn.addEventListener('click', () => {
            if (currentPage < totalPages) {
                loadProducts(currentPage); // 转换为后端页码（前端页码-1）
            }
        });
        controls.appendChild(nextBtn);
    };

    // 加载业务员（修改后）
    const loadSalesmen = () => {
        const salesmanSelect = document.getElementById('salesmanSelect');

        loadPagedData('/salesman?role=SALESMAN', (salesmen) => {
            salesmanSelect.innerHTML = '';
            const defaultOption = document.createElement('option');
            defaultOption.value = '';
            defaultOption.textContent = '请选择业务员';
            salesmanSelect.appendChild(defaultOption);

            salesmen.forEach(salesman => {
                const option = document.createElement('option');
                option.value = salesman.salesmanId;
                option.textContent = salesman.salesmanName;
                salesmanSelect.appendChild(option);

                // 填充全局业务员数据
                globalData.salesmen[salesman.salesmanId] = salesman.salesmanName;
            });
        });
    };

    // 加载仓库（修改后）
    const loadWarehouses = () => {
        const warehouseSelect = document.getElementById('warehouseSelect');

        loadPagedData('/warehouse', (warehouses) => {
            warehouseSelect.innerHTML = '';
            const defaultOption = document.createElement('option');
            defaultOption.value = '';
            defaultOption.textContent = '请选择仓库';
            warehouseSelect.appendChild(defaultOption);

            warehouses.forEach(warehouse => {
                const option = document.createElement('option');
                option.value = warehouse.warehouseId;
                option.textContent = warehouse.warehouseName;
                warehouseSelect.appendChild(option);

                // 填充全局仓库数据
                globalData.warehouses[warehouse.warehouseId] = warehouse.warehouseName;
            });
        });
    };

    // 显示商品选择模态框（修改后）
    const showProductModal = () => {
        const modal = document.getElementById('productModal');
        modal.classList.remove('hidden');

        // 初始化分页状态
        let currentProductPage = 0;
        let productPageSize = 10;
        let productSearchKeyword = '';
        let totalProductPages = 1;
        let currentProducts = []; // 新增变量存储当前商品列表

        // 渲染商品列表和分页
        const renderProducts = (products, totalPages) => {
            currentProducts = products; // 保存当前商品数据

            const productListContainer = document.getElementById('productListContainer');
            const paginationContainer = document.getElementById('productPagination');

            let productsHtml = '';
            if (products && products.length > 0) {
                // 过滤已选择的商品
                const selectedProductIds = productRows.map(row => row.productId);
                const filteredProducts = products.filter(product => !selectedProductIds.includes(product.productId));

                if (filteredProducts.length > 0) {
                    filteredProducts.forEach(product => {
                        productsHtml += `
                    <div class="flex items-center p-3 border border-gray-200 rounded-md hover:bg-gray-50 cursor-pointer"
                         data-product-id="${product.productId}">
                        <div class="w-10 h-10 rounded bg-primary/10 flex items-center justify-center text-primary">
                            <i class="fa fa-cube"></i>
                        </div>
                        <div class="ml-3 flex-1">
                            <h4 class="font-medium text-gray-800">${product.productName}</h4>
                            <p class="text-sm text-gray-500">${product.productId}</p>
                        </div>
                        <div class="text-right">
                            <span class="text-sm text-gray-600">库存: ${product.productStock || 0}</span>
                        </div>
                    </div>
                `;
                    });
                } else {
                    productsHtml = `
                <div class="text-center py-8 text-gray-500">
                    <i class="fa fa-info-circle mr-2"></i> 没有可添加的商品
                </div>
            `;
                }
            } else {
                productsHtml = `
            <div class="text-center py-8 text-gray-500">
                <i class="fa fa-exclamation-circle mr-2"></i> 未找到商品
            </div>
        `;
            }

            productListContainer.innerHTML = productsHtml;

            // 渲染分页控件
            totalProductPages = totalPages;
            renderProductPagination();

            // 添加商品点击事件
            document.querySelectorAll('#productListContainer > div[data-product-id]').forEach(card => {
                card.addEventListener('click', () => {
                    const productId = parseInt(card.getAttribute('data-product-id'));
                    // 直接从当前商品列表中查找
                    const product = currentProducts.find(p => p.productId === productId);
                    if (product) addProductToOrder(product);
                    modal.classList.add('hidden');
                });
            });
        };

        // 渲染商品分页控件
        const renderProductPagination = () => {
            const paginationContainer = document.getElementById('productPagination');
            paginationContainer.innerHTML = '';

            if (totalProductPages <= 1) return;

            // 上一页按钮
            const prevBtn = document.createElement('button');
            prevBtn.className = `px-3 py-1 border border-gray-300 rounded-md text-gray-500 hover:bg-gray-50 ${currentProductPage === 0 ? 'opacity-50 cursor-not-allowed' : ''}`;
            prevBtn.disabled = currentProductPage === 0;
            prevBtn.innerHTML = '<i class="fa fa-chevron-left"></i> 上一页';
            prevBtn.addEventListener('click', () => {
                if (currentProductPage > 0) {
                    currentProductPage--;
                    loadProducts();
                }
            });
            paginationContainer.appendChild(prevBtn);

            // 页码按钮
            const startPage = Math.max(0, currentProductPage - 2);
            const endPage = Math.min(totalProductPages - 1, currentProductPage + 2);

            for (let i = startPage; i <= endPage; i++) {
                const pageBtn = document.createElement('button');
                pageBtn.className = `px-3 py-1 border rounded-md text-gray-700 hover:bg-gray-50 ${i === currentProductPage ? 'border-primary bg-primary text-white' : ''}`;
                pageBtn.textContent = i + 1; // 前端显示从1开始
                pageBtn.addEventListener('click', () => {
                    currentProductPage = i;
                    loadProducts();
                });
                paginationContainer.appendChild(pageBtn);
            }

            // 下一页按钮
            const nextBtn = document.createElement('button');
            nextBtn.className = `px-3 py-1 border border-gray-300 rounded-md text-gray-500 hover:bg-gray-50 ${currentProductPage >= totalProductPages - 1 ? 'opacity-50 cursor-not-allowed' : ''}`;
            nextBtn.disabled = currentProductPage >= totalProductPages - 1;
            nextBtn.innerHTML = '下一页 <i class="fa fa-chevron-right"></i>';
            nextBtn.addEventListener('click', () => {
                if (currentProductPage < totalProductPages - 1) {
                    currentProductPage++;
                    loadProducts();
                }
            });
            paginationContainer.appendChild(nextBtn);
        };

        // 加载商品数据（支持分页和搜索）
        const loadProducts = () => {
            productSearchKeyword = document.getElementById('productSearchInput').value.trim();

            // 显示加载状态
            document.getElementById('productListContainer').innerHTML = `
            <div class="text-center py-8">
                <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
                <p class="mt-2 text-gray-600">加载商品中...</p>
            </div>
        `;

            // 构建除warehouseId外的其他查询参数
            const queryParams = new URLSearchParams({
                page: currentProductPage.toString(),
                size: productPageSize.toString(),
                ...(productSearchKeyword && { orderId: productSearchKeyword })
            });

            const warehouseId = document.getElementById('warehouseSelect').value;
            if (!warehouseId) {
                // 如果没有选择仓库，清空商品列表或给出提示
                document.getElementById('productListContainer').innerHTML = '';
                return;
            }

            // 构建URL：路径变量 + 查询参数
            const queryString = queryParams.toString();
            const url = `/warehouseProduct/${warehouseId}${queryString ? `?${queryString}` : ''}`;


            // 调用API加载商品（假设API路径为/product，与之前一致）
            fetch(url)
                .then(response => {
                    if (!response.ok) throw new Error(`状态码: ${response.status}`);
                    return response.json();
                })
                .then(apiResponse => {
                    if (apiResponse.code !== "200" || !apiResponse.data?.content) {
                        throw new Error(apiResponse.message || "商品数据加载失败");
                    }
                    const { content, totalPages } = apiResponse.data;
                    renderProducts(content, totalPages);
                })
                .catch(error => {
                    console.error('加载商品失败:', error);
                    document.getElementById('productListContainer').innerHTML = `
                    <div class="text-center py-8 text-red-500">
                        <i class="fa fa-exclamation-circle mr-2"></i> 加载商品失败: ${error.message}
                    </div>
                `;
                });
        };

        // 初始化搜索事件
        const searchInput = document.getElementById('productSearchInput');
        searchInput.addEventListener('input', loadProducts);
        searchInput.addEventListener('keypress', e => {
            if (e.key === 'Enter') loadProducts();
        });

        // 首次加载第一页商品
        loadProducts();
    };

    // 添加商品到订单
    const addProductToOrder = (product) => {
        // 检查商品是否已添加
        const existingIndex = productRows.findIndex(row => row.productId === product.productId);

        if (existingIndex !== -1) {
            // 如果已添加，提示用户
            Toastify({
                text: "该商品已添加到订单中",
                duration: 3000,
                gravity: "top",
                position: "right",
                backgroundColor: "#FF7D00",
            }).showToast();
            return;
        }

        // 添加商品到列表
        productRows.push({
            productId: product.productId,
            productName: product.productName,
            productCode: product.productId,
            quantity: 1
        });

        // 重新渲染商品表格
        renderProductTable();
    };

    // 渲染商品表格（修改后）
    const renderProductTable = () => {
        const productTable = document.getElementById('productTable');
        const tbody = productTable.querySelector('tbody');
        tbody.innerHTML = '';

        if (productRows.length === 0) {
            tbody.innerHTML = `
            <tr id="emptyProductRow">
                <td colspan="3" class="py-6 text-center text-gray-500">
                    <i class="fa fa-info-circle mr-2"></i> 请添加商品到订单
                </td>
            </tr>
        `;
            return;
        }

        // 渲染商品行
        productRows.forEach((row, index) => {
            const tr = document.createElement('tr');
            tr.className = 'border-b border-gray-100';

            // 通过商品ID获取商品名
            const productName = globalData.products[row.productId]?.name || '未知商品';

            tr.innerHTML = `
            <td class="py-3 px-3">
                <div class="flex items-center">
                    <div class="w-8 h-8 rounded bg-primary/10 flex items-center justify-center text-primary mr-3">
                        <i class="fa fa-cube"></i>
                    </div>
                    <div>
                        <div class="font-medium text-gray-800">${productName}</div>
                        <div class="text-sm text-gray-500">${row.productId}</div>
                    </div>
                </div>
            </td>
            <td class="py-3 px-3">
                <div class="flex items-center">
                    <input type="number" value="${row.quantity}" min="1"
                        class="w-20 px-3 py-1 border border-gray-300 rounded-md input-focus product-quantity"
                        data-index="${index}">
                </div>
            </td>
            <td class="py-3 px-3">
                <button class="text-danger hover:text-danger/80" onclick="removeProduct(${index})">
                    <i class="fa fa-trash"></i> 删除
                </button>
            </td>
        `;
            tbody.appendChild(tr);
        });

        // 添加数量变更事件监听器
        document.querySelectorAll('.product-quantity').forEach(input => {
            input.addEventListener('change', (e) => {
                const index = parseInt(e.target.getAttribute('data-index'));
                const value = parseInt(e.target.value);

                if (!isNaN(value) && value > 0) {
                    productRows[index].quantity = value;
                } else {
                    e.target.value = productRows[index].quantity;
                    Toastify({
                        text: "请输入有效的数量",
                        duration: 3000,
                        gravity: "top",
                        position: "right",
                        backgroundColor: "#f44336",
                    }).showToast();
                }
            });
        });
    };

    // 移除商品
    const removeProduct = (index) => {
        productRows.splice(index, 1);
        renderProductTable();
    };


    // 查看订单详情
    const viewOrderDetails = (orderId) => {
        currentOrderId = orderId;
        const modal = document.getElementById('orderDetailModal');
        modal.classList.remove('hidden');

        // 显示加载状态
        const modalContent = document.createElement('div');
        modalContent.className = 'bg-white rounded-lg shadow-xl w-full max-w-4xl max-h-[80vh] overflow-hidden';
        modalContent.innerHTML = `
                                  <div class="flex justify-between items-center p-4 border-b border-gray-200">
                        <h3 class="text-lg font-semibold text-gray-800">订单详情 #${orderId}</h3>
                        <button class="text-gray-500 hover:text-gray-700" onclick="document.getElementById('orderDetailModal').classList.add('hidden')">
                            <i class="fa fa-times"></i>
                        </button>
                    </div>
                    <div class="p-4">
                        <div class="animate-pulse">
                            <div class="h-6 bg-gray-200 rounded w-1/3 mb-4"></div>
                            <div class="h-4 bg-gray-200 rounded w-1/2 mb-2"></div>
                            <div class="h-4 bg-gray-200 rounded w-1/4 mb-4"></div>
                            <div class="h-6 bg-gray-200 rounded w-1/4 mb-2"></div>
                            <div class="h-4 bg-gray-200 rounded w-2/3 mb-4"></div>
                            <div class="h-6 bg-gray-200 rounded w-1/5 mb-2"></div>
                            <div class="h-4 bg-gray-200 rounded w-3/4 mb-4"></div>
                            <div class="h-6 bg-gray-200 rounded w-1/4 mb-2"></div>
                            <div class="h-4 bg-gray-200 rounded w-full mb-4"></div>
                            <div class="h-6 bg-gray-200 rounded w-1/3 mb-2"></div>
                            <div class="h-4 bg-gray-200 rounded w-full"></div>
                        </div>
                    </div>
                </div>
            `;

        modal.innerHTML = '';
        modal.appendChild(modalContent);

        // 调用API获取订单详情
        fetch(`/outStockOrder/${orderId}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP错误! 状态码: ${response.status}`);
                }
                return response.json();
            })
            .then(apiResponse => {
                if (apiResponse) {
                    const order = apiResponse;

                    // 构建订单状态标签
                    let statusClass = '';
                    let statusText = '';
                    switch (order.status) {
                        case 'pending':
                            statusClass = 'bg-blue-100 text-blue-800';
                            statusText = '待处理';
                            break;
                        case 'completed':
                            statusClass = 'bg-green-100 text-green-800';
                            statusText = '已完成';
                            break;
                        case 'failed':
                            statusClass = 'bg-red-100 text-red-800';
                            statusText = '已失败';
                            break;
                        case 'cancel':
                            statusClass = 'bg-gray-100 text-gray-800';
                            statusText = '已取消';
                            break;
                        default:
                            statusClass = 'bg-gray-100 text-gray-800';
                            statusText = '未知';
                    }

                    // 格式化日期
                    const orderDate = formatDate(order.orderDate);
                    const createTime = formatDateTime(order.orderDate);
                    const updateTime = formatDateTime(order.orderDate);

                    // 通过ID获取名称
                    const salesmanName = globalData.salesmen[order.salesmanId] || '未知业务员';
                    const warehouseName = globalData.warehouses[order.warehouseId] || '未知仓库';

                    // 格式化显示ID和名称
                    const formattedSalesman = formatIdName(order.salesmanId, salesmanName);
                    const formattedWarehouse = formatIdName(order.warehouseId, warehouseName);
                    // 构建订单详情内容
                    let orderDetailsHtml = `
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
                                <div>
                                    <h4 class="text-sm font-medium text-gray-500 mb-2">订单基本信息</h4>
                                    <div class="bg-gray-50 p-4 rounded-lg">
                                        <div class="flex justify-between mb-2">
                                            <span class="text-gray-600">订单编号:</span>
                                            <span class="font-medium">#${order.orderId}</span>
                                        </div>
                                        <div class="flex justify-between mb-2">
                                            <span class="text-gray-600">订单日期:</span>
                                            <span>${orderDate}</span>
                                        </div>
                                        <div class="flex justify-between mb-2">
                                            <span class="text-gray-600">业务员:</span>
                                            <span>${formattedSalesman || '未知业务员'}</span>
                                        </div>
                                        <div class="flex justify-between mb-2">
                                            <span class="text-gray-600">仓库:</span>
                                            <span>${formattedWarehouse || '未知仓库'}</span>
                                        </div>
                                        <div class="flex justify-between">
                                            <span class="text-gray-600">订单状态:</span>
                                            <span><span class="px-2 py-1 rounded-full text-xs font-medium ${statusClass}">${statusText}</span></span>
                                        </div>
                                    </div>
                                </div>
                                <div>
                                    <h4 class="text-sm font-medium text-gray-500 mb-2">订单处理信息</h4>
                                    <div class="bg-gray-50 p-4 rounded-lg">
                                        <div class="flex justify-between mb-2">
                                            <span class="text-gray-600">创建时间:</span>
                                            <span>${createTime}</span>
                                        </div>
                                        <div class="flex justify-between mb-2">
                                            <span class="text-gray-600">创建人:</span>
                                            <span>${order.salesmanId || '未知'}</span>
                                        </div>
                                        <div class="flex justify-between mb-2">
                                            <span class="text-gray-600">最后更新时间:</span>
                                            <span>${updateTime}</span>
                                        </div>
                                        <div class="flex justify-between mb-2">
                                            <span class="text-gray-600">更新人:</span>
                                            <span>${order.salesmanId || '未知'}</span>
                                        </div>
                                        ${order.status === 'completed' ? `
                                        <div class="flex justify-between mb-2">
                                            <span class="text-gray-600">完成时间:</span>
                                            <span>${formatDateTime(order.completeTime)}</span>
                                        </div>
                                        <div class="flex justify-between">
                                            <span class="text-gray-600">完成人:</span>
                                            <span>${salesmanName || '未知'}</span>
                                        </div>
                                        ` : ''}
                                    </div>
                                </div>
                            </div>

                            <h4 class="text-sm font-medium text-gray-500 mb-2">订单备注</h4>
                            <div class="bg-gray-50 p-4 rounded-lg mb-6">
                                <p class="text-gray-600">${order.remark || '无备注信息'}</p>
                            </div>

                            <h4 class="text-sm font-medium text-gray-500 mb-2">商品明细</h4>
                            <div class="overflow-x-auto">
                                <table class="w-full">
                                    <thead>
                                        <tr class="bg-gray-50 border border-gray-200">
                                            <th class="py-2 px-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">商品</th>
                                            <th class="py-2 px-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">数量</th>
                                            ${order.status === 'completed' ? `
                                             ` : ''}
                                        </tr>
                                    </thead>
                                    <tbody>
                        `;

                    // 添加商品明细
                    if (order.outStockDetails && order.outStockDetails.length > 0) {
                        order.outStockDetails.forEach(detail => {
                            const productId = detail.productId || 0;
                            const product = globalData.products[productId] || {};

                            // 从对象中获取name属性
                            const productName = product.name || `未知商品(ID: ${productId})`;
                            const productCode = product.code || productId;

                            orderDetailsHtml += `
                                    <tr class="border-b border-gray-100">
                                        <td class="py-3 px-3">
                                            <div class="flex items-center">
                                                <div class="w-8 h-8 rounded bg-primary/10 flex items-center justify-center text-primary mr-3">
                                                    <i class="fa fa-cube"></i>
                                                </div>
                                                <div>
                                                    <div class="font-medium text-gray-800">${productName|| '未知商品'}</div>
                                                    <div class="text-sm text-gray-500">${productCode || '未知编码'}</div>
                                                </div>
                                            </div>
                                        </td>
                                        <td class="py-3 px-3">
                                            <span class="font-medium">${detail.quantity}</span>
                                        </td>
                                        ${order.status === 'completed' ? `
                                        ` : ''}
                                    </tr>
                                `;
                        });
                    } else {
                        orderDetailsHtml += `
                                <tr>
                                    <td colspan="${order.status === 'completed' ? '3' : '2'}" class="py-4 text-center text-gray-500">
                                        无商品明细
                                    </td>
                                </tr>
                            `;
                    }

                    orderDetailsHtml += `
                                    </tbody>
                                </table>
                            </div>
                        `;

                    // 更新模态框内容
                    modalContent.innerHTML = `
                            <div class="flex justify-between items-center p-4 border-b border-gray-200">
                                <h3 class="text-lg font-semibold text-gray-800">订单详情 #${orderId}</h3>
                                <button class="text-gray-500 hover:text-gray-700" onclick="document.getElementById('orderDetailModal').classList.add('hidden')">
                                    <i class="fa fa-times"></i>
                                </button>
                            </div>
                            <div class="p-4 overflow-y-auto max-h-[calc(80vh-120px)]">
                                ${orderDetailsHtml}
                            </div>
                            <div class="flex justify-end p-4 border-t border-gray-200">
                                <button class="btn-secondary" onclick="document.getElementById('orderDetailModal').classList.add('hidden')">关闭</button>
                            </div>
                        `;
                } else {
                    // 处理错误情况
                    modalContent.innerHTML = `
                            <div class="flex justify-between items-center p-4 border-b border-gray-200">
                                <h3 class="text-lg font-semibold text-gray-800">订单详情 #${orderId}</h3>
                                <button class="text-gray-500 hover:text-gray-700" onclick="document.getElementById('orderDetailModal').classList.add('hidden')">
                                    <i class="fa fa-times"></i>
                                </button>
                            </div>
                            <div class="p-4">
                                <div class="text-center py-8">
                                    <i class="fa fa-exclamation-circle text-4xl text-red-400 mb-4"></i>
                                    <p class="text-gray-600">无法加载订单详情，请稍后重试</p>
                                </div>
                            </div>
                            <div class="flex justify-end p-4 border-t border-gray-200">
                                <button class="btn-secondary" onclick="document.getElementById('orderDetailModal').classList.add('hidden')">关闭</button>
                            </div>
                        `;
                }
            })
            .catch(error => {
                console.error('加载订单详情失败:', error);
                // 处理错误情况
                modalContent.innerHTML = `
                        <div class="flex justify-between items-center p-4 border-b border-gray-200">
                            <h3 class="text-lg font-semibold text-gray-800">订单详情 #${orderId}</h3>
                            <button class="text-gray-500 hover:text-gray-700" onclick="document.getElementById('orderDetailModal').classList.add('hidden')">
                                <i class="fa fa-times"></i>
                            </button>
                        </div>
                        <div class="p-4">
                            <div class="text-center py-8">
                                <i class="fa fa-exclamation-circle text-4xl text-red-400 mb-4"></i>
                                <p class="text-gray-600">加载订单详情失败: ${error.message}</p>
                            </div>
                        </div>
                        <div class="flex justify-end p-4 border-t border-gray-200">
                            <button class="btn-secondary" onclick="document.getElementById('orderDetailModal').classList.add('hidden')">关闭</button>
                        </div>
                    `;
            });
    };

    // 编辑订单
    const editOrder = (orderId) => {
        currentOrderId = orderId;

        // 显示表单容器
        document.getElementById('orderFormContainer').classList.remove('hidden');
        document.getElementById('orderFormContainer').scrollIntoView({ behavior: 'smooth' });

        // 更新表单标题（添加订单号）
        document.getElementById('formTitle').textContent = `编辑出库订单 #${orderId}`;

        // 重置表单
        const formContainer = document.getElementById('orderForm');
        formContainer.innerHTML = `
        <div class="border-b border-gray-200">
            <nav class="-mb-px flex space-x-8" id="orderFormTabs">
                <button type="button" class="border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm" data-tab="details">
                    <i class="fa fa-file-text-o mr-1"></i> 基本信息
                </button>
                <button type="button" class="border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm" data-tab="products">
                    <i class="fa fa-cubes mr-1"></i> 商品明细
                </button>
                <button type="button" class="border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm" data-tab="notes">
                    <i class="fa fa-sticky-note-o mr-1"></i> 备注信息
                </button>
            </nav>
        </div>

        <div class="tab-content mt-6">
            <!-- 基本信息选项卡 -->
            <div id="tab-details" class="tab-pane hidden">
                <div class="space-y-6">
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">订单日期</label>
                            <input type="datetime-local" id="orderDate" class="w-full px-3 py-2 rounded-md border border-gray-300 input-focus" required>
                            <input type="hidden" id="orderDateTimeWithSeconds" name="orderDateTimeWithSeconds">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">业务员</label>
                            <div class="relative">
                                <select id="salesmanSelect" class="w-full pl-3 pr-10 py-2 rounded-md border border-gray-300 input-focus appearance-none">
                                    <option value="">选择业务员</option>
                                </select>
                                <i class="fa fa-chevron-down absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 pointer-events-none"></i>
                            </div>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">仓库</label>
                            <div class="relative">
                                <select id="warehouseSelect" class="w-full pl-3 pr-10 py-2 rounded-md border border-gray-300 input-focus appearance-none">
                                    <option value="">选择仓库</option>
                                </select>
                                <i class="fa fa-chevron-down absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 pointer-events-none"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 商品明细选项卡 -->
            <div id="tab-products" class="tab-pane hidden">
                <div class="flex justify-between items-center mb-3">
                    <h4 class="text-base font-medium text-gray-800">订单商品明细</h4>
                    <button type="button" id="addProductBtn" class="text-primary hover:text-primary/80 flex items-center">
                        <i class="fa fa-plus-circle mr-1"></i> 添加商品
                    </button>
                </div>
                <div class="overflow-x-auto">
                    <table class="w-full" id="productTable">
                        <thead>
                            <tr class="bg-gray-50 border border-gray-200">
                                <th class="py-2 px-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">商品</th>
                                <th class="py-2 px-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">数量</th>
                                <th class="py-2 px-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr id="emptyProductRow">
                                <td colspan="3" class="py-6 text-center text-gray-500">
                                    <i class="fa fa-info-circle mr-2"></i> 请添加商品到订单
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- 备注信息选项卡 -->
            <div id="tab-notes" class="tab-pane hidden">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">备注</label>
                    <textarea id="orderRemark" rows="8" class="w-full px-3 py-2 rounded-md border border-gray-300 input-focus" placeholder="输入订单备注信息"></textarea>
                </div>
            </div>
        </div>

        <!-- 表单操作按钮 -->
        <div class="mt-6 flex justify-end space-x-3">
            <button type="button" id="cancelOrderBtn" class="btn-secondary">取消</button>
            <button type="button" id="saveOrderBtn" class="btn-primary">保存修改</button>
            <button type="button" id="confirmOrderBtn" class="btn-primary bg-success">确认更新</button>
        </div>
    `;

        // 调用API获取订单详情
        fetch(`/outStockOrder/${orderId}`)
            .then(response => {
                if (!response.ok) throw new Error(`HTTP错误! 状态码: ${response.status}`);
                return response.json();
            })
            .then(apiResponse => {
                if (apiResponse) {
                    const order = apiResponse;

                    // 自动填充当前日期时间
                    autoFillOrderDateTime();

                    // 填充订单日期
                    const orderDate = new Date(order.orderDate);
                    const formattedDate = orderDate.toISOString().slice(0, 16);
                    document.getElementById('orderDate').value = formattedDate;
                    document.getElementById('orderDateTimeWithSeconds').value = orderDate.toISOString().slice(0, 19);


                    // 填充业务员下拉框
                    const salesmanSelect = document.getElementById('salesmanSelect');
                    if (salesmanSelect && globalData.salesmen) {
                        salesmanSelect.innerHTML = '<option value="">选择业务员</option>';
                        Object.entries(globalData.salesmen).forEach(([id, name]) => {
                            const option = document.createElement('option');
                            option.value = id;
                            option.textContent = name;
                            salesmanSelect.appendChild(option);
                        });
                        if (order.salesmanId) {
                            salesmanSelect.value = order.salesmanId;
                        }
                    }

                    // 填充仓库下拉框
                    const warehouseSelect = document.getElementById('warehouseSelect');
                    if (warehouseSelect && globalData.warehouses) {
                        warehouseSelect.innerHTML = '<option value="">选择仓库</option>';
                        Object.entries(globalData.warehouses).forEach(([id, name]) => {
                            const option = document.createElement('option');
                            option.value = id;
                            option.textContent = name;
                            warehouseSelect.appendChild(option);
                        });
                        if (order.warehouseId) {
                            warehouseSelect.value = order.warehouseId;
                        }
                    }

                    // 填充备注
                    const orderRemark = document.getElementById('orderRemark');
                    if (orderRemark) {
                        orderRemark.value = order.remark || '';
                    }

                    // 处理商品明细
                    productRows = [];
                    if (order.outStockDetails && order.outStockDetails.length > 0) {
                        order.outStockDetails.forEach(detail => {
                            const productId = detail.productId || 0;
                            const product = globalData.products[productId] || {
                                name: `未知商品(ID: ${productId})`,
                                code: productId
                            };
                            productRows.push({
                                productId: product.code,
                                productName: product.name,
                                quantity: detail.quantity || 1
                            });
                        });
                    }

                    // 初始化选项卡切换功能（数据填充后再初始化）
                    const tabs = document.querySelectorAll('#orderFormTabs button');
                    tabs.forEach(tab => {
                        tab.addEventListener('click', () => {
                            // 移除所有活动状态
                            tabs.forEach(t => {
                                t.classList.remove('border-primary', 'text-primary');
                                t.classList.add('border-transparent', 'text-gray-500');
                            });

                            // 添加当前活动状态
                            tab.classList.remove('border-transparent', 'text-gray-500');
                            tab.classList.add('border-primary', 'text-primary');

                            // 隐藏所有面板
                            document.querySelectorAll('.tab-pane').forEach(pane => {
                                pane.classList.add('hidden');
                            });

                            // 显示当前面板
                            const tabId = tab.getAttribute('data-tab');
                            document.getElementById(`tab-${tabId}`).classList.remove('hidden');

                            // 如果切换到商品面板，确保表格已渲染
                            if (tabId === 'products') {
                                renderProductTable();
                            }
                        });
                    });

                    // 渲染商品表格
                    renderProductTable();

                    // 根据订单状态决定默认选项卡
                    const defaultTab = productRows.length > 0 ? 'products' : 'details';

                    // 激活默认选项卡（直接设置样式，不触发点击事件）
                    tabs.forEach(tab => {
                        if (tab.getAttribute('data-tab') === defaultTab) {
                            // 设置选项卡样式
                            tab.classList.remove('border-transparent', 'text-gray-500');
                            tab.classList.add('border-primary', 'text-primary');

                            // 显示对应面板
                            document.getElementById(`tab-${defaultTab}`).classList.remove('hidden');
                        } else {
                            tab.classList.remove('border-primary', 'text-primary');
                            tab.classList.add('border-transparent', 'text-gray-500');
                        }
                    });

                    // 添加事件监听器
                    document.getElementById('addProductBtn').addEventListener('click', showProductModal);
                    document.getElementById('cancelOrderBtn').addEventListener('click', hideOrderForm);
                    document.getElementById('saveOrderBtn').addEventListener('click', saveOrder);
                    document.getElementById('confirmOrderBtn').addEventListener('click', confirmOrder);
                } else {
                    // 处理错误情况
                    const formContainer = document.getElementById('orderForm');
                    formContainer.innerHTML = `
                    <div class="py-8 text-center">
                        <i class="fa fa-exclamation-circle text-4xl text-red-400 mb-4"></i>
                        <p class="text-gray-600">无法加载订单数据，请稍后重试</p>
                        <button type="button" id="cancelOrderBtn" class="btn-secondary mt-4">返回</button>
                    </div>
                `;
                    document.getElementById('cancelOrderBtn').addEventListener('click', hideOrderForm);
                }
            })
            .catch(error => {
                console.error('加载订单数据失败:', error);
                const formContainer = document.getElementById('orderForm');
                formContainer.innerHTML = `
                <div class="py-8 text-center">
                    <i class="fa fa-exclamation-circle text-4xl text-red-400 mb-4"></i>
                    <p class="text-gray-600">加载订单数据失败: ${error.message}</p>
                    <button type="button" id="cancelOrderBtn" class="btn-secondary mt-4">返回</button>
                </div>
            `;
                document.getElementById('cancelOrderBtn').addEventListener('click', hideOrderForm);
            });
    };

    //执行出库
    const executeOrder = (orderId) => {
        currentOrderId = orderId;

        // 确认对话框
        if (!confirm("确定要执行此出库订单吗？执行后将更新库存数据。")) {
            return;
        }

        // 显示加载状态
        const loadingToast = Toastify({
            text: "正在处理出库操作...",
            duration: -1,
            gravity: "top",
            position: "right",
            backgroundColor: "#2196F3",
        }).showToast();

        // 调用API执行出库
        fetch(`/outStockOrder/${orderId}/execute`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
        })
            .then(response => {
                // 对于204响应，不需要解析JSON
                if (response.status === 204) {
                    return null; // 表示操作成功但无返回数据
                }
                if (!response.ok) {
                    // 尝试解析响应中的JSON错误信息
                    return response.json().catch(() => ({})) // 解析失败则返回空对象
                        .then(errorData => {
                            // 构建包含HTTP状态码和服务器错误信息的错误
                            const errorMessage = errorData.message
                                ? `HTTP错误 ${response.status}: ${errorData.message}`
                                : `HTTP错误 ${response.status}`;
                            throw new Error(errorMessage);
                        });
                }
                return response.json();
            })
            .then(apiResponse => {
                // 关闭加载提示
                loadingToast.hideToast();

                if (apiResponse === null) {
                    // 处理204响应
                    Toastify({
                        text: "出库操作成功，库存已更新",
                        duration: 3000,
                        gravity: "top",
                        position: "right",
                        backgroundColor: "#4CAF50",
                    }).showToast();

                    // 刷新订单列表
                    loadOrders();
                } else if (apiResponse) {
                    // 处理成功响应（如有数据返回）
                    // 处理错误响应
                    const errorMsg = apiResponse && apiResponse.message
                        ? apiResponse.message
                        : '出库操作失败：未知错误';
                    Toastify({
                        text: errorMsg,
                        duration: 3000,
                        gravity: "top",
                        position: "right",
                        backgroundColor: "#4CAF50",
                    }).showToast();

                    // 刷新订单列表
                    loadOrders();
                } else {
                    // 处理错误响应
                    const errorMsg = apiResponse && apiResponse.message
                        ? apiResponse.message
                        : '出库操作失败：未知错误';
                    Toastify({
                        text: errorMsg,
                        duration: 3000,
                        gravity: "top",
                        position: "right",
                        backgroundColor: "#f44336",
                    }).showToast();
                }
            })
            .catch(error => {
                // 关闭加载提示
                loadingToast.hideToast();

                console.error('执行出库操作失败:', error);
                Toastify({
                    text: `出库操作失败: ${error.message}`,
                    duration: 3000,
                    gravity: "top",
                    position: "right",
                    backgroundColor: "#f44336",
                }).showToast();
            });
    };


    // 取消订单
    const cancelOrder = (orderId) => {
        currentOrderId = orderId;

        // 确认对话框
        if (!confirm("确定要删除此出库订单吗？此操作不可撤销。")) {
            return;
        }

        // 显示加载状态
        const loadingToast = Toastify({
            text: "正在删除订单...",
            duration: -1,
            gravity: "top",
            position: "right",
            backgroundColor: "#2196F3",
        }).showToast();

        // 调用API取消订单
        fetch(`/outStockOrder/${orderId}`, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json',
            },
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP错误! 状态码: ${response.status}`);
                }
                // 对于204响应，不需要解析JSON
                if (response.status === 204) {
                    return null; // 表示操作成功但无返回数据
                }
                return response.json();
            })
            .then(apiResponse => {
                // 关闭加载提示
                loadingToast.hideToast();

                if (apiResponse === null) {
                    // 处理204响应
                    Toastify({
                        text: "订单已删除",
                        duration: 3000,
                        gravity: "top",
                        position: "right",
                        backgroundColor: "#4CAF50",
                    }).showToast();

                    // 刷新订单列表
                    loadOrders();
                } else {
                    const errorMsg = apiResponse && apiResponse.message
                        ? apiResponse.message
                        : '删除订单失败：未知错误';
                    Toastify({
                        text: errorMsg,
                        duration: 3000,
                        gravity: "top",
                        position: "right",
                        backgroundColor: "#f44336",
                    }).showToast();
                }
            })
            .catch(error => {
                // 关闭加载提示
                loadingToast.hideToast();

                console.error('删除订单失败:', error);
                Toastify({
                    text: `删除订单失败: ${error.message}`,
                    duration: 3000,
                    gravity: "top",
                    position: "right",
                    backgroundColor: "#f44336",
                }).showToast();
            });
    };

    // 验证订单表单
    const validateOrderForm = () => {
        let isValid = true;
        const errorMessages = [];


        // 验证业务员
        const salesmanSelect = document.getElementById('salesmanSelect');
        if (!salesmanSelect.value) {
            isValid = false;
            errorMessages.push("请选择业务员");
            highlightInputError(salesmanSelect);
        } else {
            removeInputErrorHighlight(salesmanSelect);
        }

        // 验证仓库
        const warehouseSelect = document.getElementById('warehouseSelect');
        if (!warehouseSelect.value) {
            isValid = false;
            errorMessages.push("请选择仓库");
            highlightInputError(warehouseSelect);
        } else {
            removeInputErrorHighlight(warehouseSelect);
        }

        // 验证商品明细
        if (productRows.length === 0) {
            isValid = false;
            errorMessages.push("订单必须包含至少一个商品");
            // 高亮商品表格区域
            const productTable = document.getElementById('productTable');
            productTable.classList.add('border-red-500');
            setTimeout(() => {
                productTable.classList.remove('border-red-500');
            }, 3000);
        }

        // 显示错误信息
        if (!isValid) {
            let errorMessage = "请修正以下错误:\n";
            errorMessages.forEach(msg => {
                errorMessage += `- ${msg}\n`;
            });
            alert(errorMessage);
        }

        return isValid;
    };

    // 构建订单数据（修改后）
    const buildOrderData = () => {
        return {
            orderId: currentOrderId,
            orderDate: document.getElementById('orderDateTimeWithSeconds').value || document.getElementById('orderDate').value + ':00',
            salesmanId: document.getElementById('salesmanSelect').value,
            warehouseId: document.getElementById('warehouseSelect').value,
            remark: document.getElementById('orderRemark').value,
            outStockDetails: productRows.map(row => ({
                productId: row.productId,
                quantity: row.quantity
            }))
        };
    };

    // 高亮输入错误
    const highlightInputError = (element) => {
        element.classList.add('border-red-500');
        setTimeout(() => {
            element.classList.remove('border-red-500');
        }, 3000);
    };

    // 移除输入错误高亮
    const removeInputErrorHighlight = (element) => {
        element.classList.remove('border-red-500');
    };

    // 格式化日期 (YYYY-MM-DD)
    const formatDate = (dateString) => {
        if (!dateString) return '';
        const date = new Date(dateString);
        return date.toISOString().split('T')[0];
    };

    // 格式化日期用于输入框
    const formatDateForInput = (dateString) => {
        if (!dateString) return '';
        const date = new Date(dateString);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    };

    // 格式化日期时间 (YYYY-MM-DD HH:MM:SS)
    const formatDateTime = (dateString) => {
        if (!dateString) return '';
        const date = new Date(dateString);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    };
    // 初始化侧边栏导航
    const initSidebarNavigation = () => {
        // 获取所有菜单项
        const menuItems = document.querySelectorAll('.sidebar-menu-item');

        // 为每个菜单项添加点击事件
        menuItems.forEach(item => {
            item.addEventListener('click', () => {
                // 移除所有菜单项的活动状态
                menuItems.forEach(i => i.classList.remove('bg-primary/10', 'text-primary'));

                // 添加当前菜单项的活动状态
                item.classList.add('bg-primary/10', 'text-primary');
            });
        });
    };

    // 设置当前页面活动菜单项
    const setCurrentPageActive = () => {
        // 获取当前页面路径
        const currentPath = window.location.pathname;

        // 获取所有菜单项
        const menuItems = document.querySelectorAll('.sidebar-menu-item');

        // 查找匹配的菜单项
        menuItems.forEach(item => {
            const href = item.getAttribute('href');
            if (href && currentPath.includes(href)) {
                item.classList.add('bg-primary/10', 'text-primary');
            }
        });
    };
</script>
</body>
</html>